const { User } = require('../model')

const register = async (req, res, next) => {
  try {
    const user = new User(req.body.user)
    await user.save()
    res.json(user)
  } catch (error) {
    next(error)
  }
}

async function login(req, res, next) {
  try {
    const { username, password } = req.body.user
    const loginUser = await User.findOne({
      username,
      password,
    })

    res.json(loginUser)
  } catch (error) {
    next(error)
  }
}

async function getCurrentUser(req, res, next) {
  try {
    const { _id } = req.query
    const user = await User.findById(_id)
    await user.populate('friends').execPopulate()
    res.json(user)
  } catch (error) {
    next(error)
  }
}

const addFriend = async (req, res, next) => {
  try {
    const { currentUserId, targetUsername } = req.body

    const targetUser = await User.findOne({
      username: targetUsername,
    })
    const currentUser = await User.findById(currentUserId)

    const targetUserId = targetUser._id

    const targetUserFriends = targetUser.friends
    const currentUserFriends = currentUser.friends

    let flag = false

    if (targetUserFriends.indexOf(currentUserId) === -1) {
      targetUser.friends.push(currentUserId)
    }
    if (currentUserFriends.indexOf(targetUserId) === -1) {
      currentUser.friends.push(targetUserId)
    }

    await targetUser.save()
    await currentUser.save()

    res.json({
      msg: '朋友添加成功',
    })
  } catch (error) {
    next(error)
  }
}

module.exports = {
  register,
  login,
  getCurrentUser,
  addFriend,
}
